package dao

import (
	"database/sql"
	"htdemo.com/goim/public/imctx"
	"htdemo.com/goim/public/logger"
	"htdemo.com/goim/public/transfer"
	"htdemo.com/mycommon/datastruct"
	"time"
)

type contactsDao struct{}

var ContactsDao = new(contactsDao)

func (cd *contactsDao) GetContactsList(ctx *imctx.Context, uid int64) (contactsList []transfer.RecentContacts) {
	set := datastruct.NewSetWithParseKeyFunc(func(e interface{}) (key interface{}) {
		rc := e.(*transfer.RecentContacts)
		return rc.Uid
	})
	//哪些人给用户发了消息
	rows, err := ctx.Session.Query(`SELECT id, nickname,  sex, avatar  
		FROM t_user  WHERE id IN (SELECT sender_id FROM t_message WHERE receiver_id = ? GROUP BY sender_id);`, uid)
	if err != nil {
		logger.Sugar.Error(err)
		return
	}
	parseSql(rows, set)
	for _, v := range set.ToArr() {
		rc := v.(*transfer.RecentContacts)
		//未读消息数量
		row := ctx.Session.QueryRow(`SELECT  COUNT(DISTINCT message_id)  FROM t_message 
			WHERE read_type = 1 AND  user_id = ? AND sender_id = ? AND receiver_id =  ?;`, uid, rc.Uid, uid)
		_ = row.Scan(&rc.Total)
		//最后1条信息
		row = ctx.Session.QueryRow(`SELECT content, type, send_time FROM t_message 
			WHERE user_id = ? AND sender_id = ? AND receiver_id = ? ORDER BY send_time DESC LIMIT 1;`, uid, rc.Uid, uid)
		_ = row.Scan(&rc.Content, &rc.MsgCategory, &rc.SendTime)
		//contactsList = append(contactsList, rc)
	}
	//用户发给了哪些人
	rows, err = ctx.Session.Query(`SELECT id, nickname,  sex, avatar  
		FROM t_user  WHERE id IN (SELECT receiver_id FROM t_message WHERE sender_id = ? GROUP BY receiver_id);`, uid)
	if err != nil {
		logger.Sugar.Error(err)
		return
	}
	parseSql(rows, set)
	for _, v := range set.ToArr() {
		rc := v.(*transfer.RecentContacts)
		//最后1条信息
		content := ""
		msgCategory := 0
		var t time.Time
		row := ctx.Session.QueryRow(`SELECT content, type, send_time FROM t_message 
			WHERE user_id = ? AND sender_id = ? AND receiver_id = ? ORDER BY send_time DESC LIMIT 1;`, uid, uid, rc.Uid)
		_ = row.Scan(&content, &msgCategory, &t)
		if t.After(rc.SendTime) {
			rc.Content = content
			rc.MsgCategory = uint8(msgCategory)
			rc.SendTime = t
		}
		contactsList = append(contactsList, *rc)
	}
	//使用冒泡排序对所有消息进行排序
	times := 0
	for i := 0; i < len(contactsList)-1; i++ { //时间排序,由大到小
		flag := false
		for j := 1; j < len(contactsList)-i; j++ {
			//if contactsList[j-1].SendTime < contactsList[j].SendTime {
			if contactsList[j-1].SendTime.Before(contactsList[j].SendTime) {
				times++
				tmp := contactsList[j-1]
				contactsList[j-1] = contactsList[j]
				contactsList[j] = tmp
				flag = true
			}
		}
		if !flag {
			break
		}
	}
	return
}

func parseSql(rows *sql.Rows, set *datastruct.HashSet) {
	for rows.Next() {
		contacts := new(transfer.RecentContacts)
		_ = rows.Scan(&contacts.Uid, &contacts.NickName, &contacts.Sex, &contacts.Avatar)
		if !set.Exists(contacts) {
			set.Add(contacts)
		}
	}
}
